#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   schemas.py
@Time    :   2024/02/20 16:09:14
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
import traceback
from typing import Any, Optional
from ninja_schema import ModelSchema,Schema


class CoreModelSchema(ModelSchema):
    def create(self, **kwargs: Any) -> Any:
        """重写函数创建对象的方法"""
        model_class = self.Config.model
        data = self.dict()
        data.update(kwargs)
        try:
            instance = model_class._default_manager.create(**data)
            return instance
        except TypeError:
            tb = traceback.format_exc()
            msg = (
                "Got a `TypeError` when calling `%s.%s.create()`. "
                "This may be because you have a writable field on the "
                "serializer class that is not a valid argument to "
                "`%s.%s.create()`. You may need to make the field "
                "read-only, or override the %s.create() method to handle "
                "this correctly.\nOriginal exception was:\n %s"
                % (
                    model_class.__name__,
                    model_class._default_manager.name,
                    model_class.__name__,
                    model_class._default_manager.name,
                    self.__class__.__name__,
                    tb,
                )
            )
            raise TypeError(msg)

    def update(self, instance: Any, **kwargs: Any) -> Any:
        """
        Args:
            instance (Any): 对象实例。
            **kwargs (Any): 关键字参数。
        Returns:
            Any: 对象实例。
        Raises:
            Exception: 如果实例为空。
        Examples:
            >>> instance = SomeClass()
            >>> instance.update(name='John', age=25)
            >>> instance.save()
        """
        if not instance:
            raise Exception("需要传入实例")
        data = self.dict(exclude_none=True)
        data.update(kwargs)
        for attr, value in data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance

    def save(self, instance: Optional[Any] = None, **kwargs: Any) -> Any:
        if instance:
            result = self.update(instance, **kwargs)
            assert result is not None, "`update()` did not return an object instance."
        else:
            result = self.create(**kwargs)
            assert result is not None, "`create()` did not return an object instance."
        return result



class MessageSchema(Schema):
    message: str
    
    
class ErrorSchema(Schema):
    message: str  

    


